package com.xinqi.common.redis.topic;

import com.xinqi.common.redis.topic.api.TopicEventListener;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.redisson.spring.starter.RedissonAutoConfiguration;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;

import java.util.List;

/**
 * redisson 消息队列配置
 *
 * @author linkai
 * @date 2023/7/6
 */
@Slf4j
@AutoConfiguration
@AutoConfigureAfter({RedissonAutoConfiguration.class})
public class TopicConfig {
    private final RedissonClient redissonClient;

    @SuppressWarnings("rawtypes")
    private final List<TopicEventListener> eventListeners;

    public TopicConfig(ObjectProvider<RedissonClient> redissonClient,
                       @SuppressWarnings("rawtypes") ObjectProvider<List<TopicEventListener>> eventListeners) {
        this.redissonClient = redissonClient.getIfAvailable();
        this.eventListeners = eventListeners.getIfAvailable();
    }

    @Bean
    public TopicHelp topicHelp() {
        return new TopicHelp(redissonClient);
    }

    @Bean
    public TopicBasePostProcessor topicBasePostProcessor(TopicHelp topicHelp) {
        return new TopicBasePostProcessor(topicHelp);
    }

    @Bean
    public CommandLineRunner examTopicListenerRunner(TopicHelp topicHelp) {
        return args -> {
            if (eventListeners == null || eventListeners.isEmpty()) {
                return;
            }
            eventListeners.forEach(v -> {
                //noinspection unchecked
                topicHelp.addListener(v.topicName(), v.getMsgType(), v);
            });
        };
    }
}
